/* eslint-disable no-unused-expressions */
/* eslint-disable react/no-unused-state */
/* eslint-disable block-scoped-var */
/* eslint-disable eqeqeq */
/* eslint-disable no-var */
/* eslint-disable vars-on-top */
/* eslint-disable array-callback-return */
/* eslint-disable no-param-reassign */
/* eslint-disable no-return-assign */
/* eslint-disable jsx-a11y/alt-text */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  DownloadOutlined,
  DownOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  Modal,
  message,
  Badge,
  Tabs,
  Tooltip,
  DatePicker,
  Radio,
  Divider,
  Dropdown,
  Menu,
  Table,
  Cascader,
  Alert,
  Select,
} from 'antd';
import queryString from 'query-string';
import router from 'umi/router';
import moment from 'moment';
import Link from 'umi/link';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SendRecvSupplier from '../../components/SendRecvSupplier';
import Area from '../../components/Area';
// import ProTable from '../../components/ProTable';
import proIcon from '../../../assets/proIcon.png';
import TextOverFlow from '../../components/TextOverFlow';
import ProTable from '@/pages/components/Problem/ProblemPage/ProTable';
import ProExportBtn from '@/pages/components/Problem/ProblemPage/ProExportBtn';
import ProModal from '@/pages/components/Problem/ProblemPage/ProModal';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import downloadFile, { getProPagination } from '@/utils/utils';
import { checkPermissions } from '@/utils/authority';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const { TextArea } = Input;
const { Option } = Select;

@connect(({ adjusttaskrec, loading, publicdata: { probTypeList, sendRecvSuppList } }) => ({
  loading: loading.effects['adjusttaskrec/getcustNamesList'] ? false : loading.models.adjusttaskrec,
  cancelReceiveLoading: loading.effects['adjusttaskrec/cancelReceive'],
  tabList: adjusttaskrec.tabList,
  activeKey: adjusttaskrec.activeKey,
  pageData: adjusttaskrec.pageData,
  countVo: adjusttaskrec.countVo,
  formFieldsValue: adjusttaskrec.formFieldsValue,
  expandForm: adjusttaskrec.expandForm,
  editFlag: adjusttaskrec.editFlag,
  probTypeList,
  custList: adjusttaskrec.custList,
  sendRecvSuppList,
  downloadParams: adjusttaskrec.downloadParams,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      selectedRows: [],
      selectedRowKeys: [],
      cancelReceiveVisible: false, // 取消接单办理备注
      receiveModal: false,
      secondaryList: [], // 工伤二级户
      injecList: [],
      confirmLoading: false,
      proTable: {},
      proVisible: false,
    };
    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    const {
      location,
      activeKey,
      dispatch,
      pageData: { pagination },
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    dispatch({
      type: 'adjusttaskrec/updateModelData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    dispatch({
      type: 'adjustdetailrec/updateModelData',
      payload: {
        accuWageFlag: false,
      },
    });
    const proPagination = getProPagination(tempActiveKey, '4', pagination);
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(tempActiveKey, proPagination.current, proPagination.pageSize);
    }
    this.getCustList(null);
  }

  // 选择签约方
  getSuppId = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'adjusttaskrec/updateModelData',
      payload: {
        custList: [],
      },
    });
    const { sendRecvSuppList, form } = this.props;
    form.resetFields(['custId']);
    sendRecvSuppList.map(item => {
      if (!e) {
        this.getCustList(null);
      }
      if (item.suppId == e) {
        this.getCustList(item.suppId);
      }
      return true;
    });
  };

  // 获取客户的下拉
  getCustList = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'adjusttaskrec/getcustNamesList',
      payload: {
        suppId: e,
      },
    });
  };

  // 获取列表
  getList = (activeKey = '1', currentPage = 1, pageSize = 10, editFlags, isClear = true) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch, form, editFlag } = this.props;
    form.validateFields((err, fieldsValue) => {
      delete fieldsValue.remark;
      if (err) return;
      dispatch({
        type: 'adjusttaskrec/updateTabListQuery',
        payload: { formFieldsValue: fieldsValue, activeKey },
      });
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'empName' || key === 'idCode') {
          fieldsValue[key] = (fieldsValue[key] && fieldsValue[key].trim()) || null;
        }
        if (key === 'operTime') {
          formFieldsValue.operTimeStart =
            (fieldsValue.operTime &&
              fieldsValue.operTime[0] &&
              fieldsValue.operTime[0].format('YYYY-MM-DD')) ||
            null;
          formFieldsValue.operTimeEnd =
            (fieldsValue.operTime &&
              fieldsValue.operTime[1] &&
              fieldsValue.operTime[1].format('YYYY-MM-DD')) ||
            null;
        }
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
        delete formFieldsValue.operTime;
      });
      const pageArg = { currentPage, pageSize };
      if (editFlags && editFlags !== 'all') {
        var values = {
          busiType: '3',
          hdlState: activeKey,
          ...formFieldsValue,
          pageArg,
          editFlag: editFlags,
        };
      } else if (editFlags == 'all' || editFlag == 'all') {
        // eslint-disable-next-line no-redeclare
        var values = {
          busiType: '3',
          hdlState: activeKey,
          ...formFieldsValue,
          pageArg,
        };
      } else {
        // eslint-disable-next-line no-redeclare
        var values = {
          busiType: '3',
          hdlState: activeKey,
          ...formFieldsValue,
          pageArg,
          editFlag,
        };
      }
      // if (activeKey === '4') {
      //   dispatch({
      //     type: 'adjusttaskrec/fetchProbList',
      //     payload: {
      //       ...values,
      //       busiType: '3',
      //     },
      //   });
      // } else {
      //   dispatch({
      //     type: 'adjusttaskrec/fetchList',
      //     payload: values,
      //   });
      // }

      const downloadParams = {
        ...formFieldsValue,
        busiType: 10,
        hdlState: activeKey,
        editFlag,
      };
      dispatch({
        type: 'adjusttaskrec/updateModelData',
        payload: {
          downloadParams,
        },
      });

      if (activeKey && Number(activeKey) === 4) {
        setTimeout(() => {
          const { proTable } = this.state;
          const proFormFieldsValue = { ...downloadParams };
          if (proTable.searchList) {
            proTable.searchList(proFormFieldsValue, currentPage, pageSize);
          }
        });
      } else {
        dispatch({
          type: 'adjusttaskrec/fetchList',
          payload: values,
        });
      }

      // console.log(values);
      // this.setState({
      //   formValues: values,
      // });
    });
  };

  // 回单
  adjustReceipt = () => {
    const { selectedRows, selectedRowKeys } = this.state;
    const { dispatch, activeKey } = this.props;
    if (selectedRows.length) {
      // eslint-disable-next-line no-empty
      if (selectedRows.length > 1) {
        Modal.confirm({
          icon: <QuestionCircleOutlined />,
          title: '温馨提示',
          content: '选择多条无法修改，会直接批量回单。如想修改内容可单独修改或单条数据回单',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            dispatch({
              type: 'adjusttaskrec/reveSome',
              payload: { taskIds: selectedRowKeys },
              callback: response => {
                if (response.success) {
                  this.setState({ selectedRowKeys: [], selectedRows: [] }, () => {
                    this.getList(activeKey);
                  });
                } else {
                  message.warning(`${response.message || '回单失败！'}`);
                }
              },
            });
          },
        });
      } else {
        router.push(
          `/receiveordermanage/adjusttask/update?recvOrdAdjTaskId=${selectedRowKeys[0]}&adjType=${
            selectedRows[0].adjType
          }`
        );
      }
    } else {
      message.warning('请选择一条数据进行回单！');
    }
  };

  // 获取页签数量
  getTabNum = (activeKey, currentPage = 1, pageSize = 10) => {
    const { dispatch, form, editFlag } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formFieldsValues = fieldsValue;
      formFieldsValues.hdlState = activeKey;
      dispatch({
        type: 'adjusttaskrec/updateTabListQuery',
        payload: { formFieldsValue: formFieldsValues, activeKey },
      });
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'empName' || key === 'idCode') {
          fieldsValue[key] = (fieldsValue[key] && fieldsValue[key].trim()) || null;
        }
        if (key === 'operTime') {
          formFieldsValue.operTimeStart =
            (fieldsValue.operTime &&
              fieldsValue.operTime[0] &&
              fieldsValue.operTime[0].format('YYYY-MM-DD')) ||
            null;
          formFieldsValue.operTimeEnd =
            (fieldsValue.operTime &&
              fieldsValue.operTime[1] &&
              fieldsValue.operTime[1].format('YYYY-MM-DD')) ||
            null;
        }
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
        delete formFieldsValue.operTime;
      });
      formFieldsValue.hdlState = activeKey;
      const checkHasValue = Object.keys(fieldsValue).some(
        key => Boolean(fieldsValue[key]) !== false
      );
      if (!checkHasValue) {
        this.getList(activeKey, currentPage, pageSize);
        return;
      }
      this.setState({
        selectedRows: [],
        selectedRowKeys: [],
      });
      formFieldsValue.hdlState = activeKey;
      const values = {
        ...formFieldsValue,
      };

      this.setState({
        formValues: formFieldsValue,
      });
      dispatch({
        type: 'adjusttaskrec/fetchTabNum',
        payload: { formFieldsValue: values, currentPage, pageSize },
      });
      if (activeKey === '4') {
        const downloadParams = {
          ...formFieldsValue,
          busiType: 10,
          hdlState: activeKey,
          editFlag,
        };
        dispatch({
          type: 'adjusttaskrec/updateModelData',
          payload: {
            downloadParams,
          },
        });
      }
    });
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'adjusttaskrec/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({
      selectedRows,
      selectedRowKeys,
    });
  };

  // 标记问题人员Modal显示隐藏
  showModal = flag => {
    const { form } = this.props;
    const { selectedRows } = this.state;
    form.resetFields();
    if (selectedRows.length) {
      this.setState({
        proVisible: flag,
      });
    } else {
      message.warning('请至少选择一项');
    }
  };

  // 标记问题人员取消
  toggleProModal = flag => {
    this.setState({
      proVisible: flag,
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize, undefined, false);
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'adjusttaskrec/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({ operTime: null });
  };

  // 接单
  receive = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认发单当前条件下所有数据',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.receiveTask();
        },
      });
    } else {
      this.receiveTask();
    }
  };

  // 接单任务
  receiveTask = () => {
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    dispatch({
      type: 'adjusttaskrec/receiveTask',
      payload: { taskIds: selectedRowKeys },
    }).then(response => {
      if (response && response.success) {
        // 有值
        if (response.data) {
          // eslint-disable-next-line no-unused-vars
          if (response.data.flag) {
            response.data.injSecDets.map(item => {
              if (item.injSecList && item.injSecList.length) {
                item.injSecList.map(values => {
                  values.value = values.accoId;
                  values.label = values.accoName;
                  values.isLeaf = (values.injSecAccoDtos && false) || true;
                  if (values.injSecAccoDtos && values.injSecAccoDtos.length) {
                    const children = [];
                    values.injSecAccoDtos.map(c => {
                      children.push({
                        value: c.injSecAccoId,
                        label: c.injSecAccoName,
                        isLeaf: true,
                      });
                    });
                    values.children = children;
                  }
                });
                // let secAccuIntValue = [];
                // if (
                //   item.injSecList.length === 1 &&
                //   item.injSecList[0].injSecAccoDtos &&
                //   item.injSecList[0].injSecAccoDtos.length === 1
                // ) {
                //   secAccuIntValue = [
                //     item.injSecList[0].accoId,
                //     item.injSecList[0].injSecAccoDtos[0].injSecAccoId,
                //   ];

                //   // eslint-disable-next-line react/destructuring-assignment
                //   this.props.form.setFieldsValue({
                //     [`secondary${index}`]: secAccuIntValue || undefined,
                //   });
                // }
              }
            });
            this.setState({ receiveModal: true, secondaryList: response.data.injSecDets });
          } else {
            message.success('接单成功！');
            this.getList();
            this.setState({
              selectedRows: [],
              selectedRowKeys: [],
            });
          }
        }
      } else {
        message.warning(`${response.message || '接单失败！'}`);
      }
    });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { location } = this.props;
    router.push({
      pathname: location.pathname,
      query: {
        activeKey,
      },
    });

    this.setState({ selectedRows: [], selectedRowKeys: [] }, () => {
      this.getList(activeKey);
    });
  };

  // 通知签约方
  // notifycontg = () => {
  //   const { dispatch, activeKey } = this.props;
  //   const { selectedRowKeys, selectedRows } = this.state;
  //   if (selectedRowKeys.length) {
  //     const isNoticed = selectedRows.some(item => item.sendSuppFlag && item.sendSuppFlag === 1);
  //     if (isNoticed) {
  //       return message.warning('所选问题人员中含有已通知完成的人员，请选择未通知签约方的人员！');
  //     }
  //     dispatch({
  //       type: 'reducemprec/noticeSign',
  //       payload: {
  //         detIds: selectedRowKeys,
  //         busiType: '3',
  //       },
  //       callback: response => {
  //         if (response.success) {
  //           message.success('通知成功！');
  //           this.setState({ selectedRowKeys: [], selectedRows: [] }, () => {
  //             this.getList(activeKey);
  //           });
  //         } else {
  //           message.warning(`${response.message || '通知失败！'}`);
  //         }
  //       },
  //     });
  //   } else {
  //     message.warning('请至少选择一项');
  //   }
  //   return true;
  // };

  // 问题人员导出数据
  export = () => {
    // eslint-disable-next-line react/destructuring-assignment
    if (!this.state.selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    // eslint-disable-next-line no-unused-vars
    const { formValues, selectedRows, selectedRowKeys } = this.state;
    const { formFieldsValue, activeKey } = this.props;
    if (activeKey === '4') {
      // 问题人员
      const params = {
        ...formFieldsValue,
        busiType: '3',
        hdlState: activeKey,
        detIds: selectedRowKeys,
      };
      downloadFile(params, '/nsApi/recvProb/export', 'POST');
    } else {
      const params = {
        ...formFieldsValue,
        hdlState: activeKey,
        busiType: '3',
        recvAdjTaskIds: selectedRowKeys,
      };
      downloadFile(params, '/nsApi/recvService/adjs/export', 'POST');
    }
  };

  // 有无修改
  editFlag = e => {
    e.preventDefault();
    const { dispatch, activeKey } = this.props;
    dispatch({
      type: 'adjusttaskrec/updateModelData',
      // payload: { editFlag: e.target.value === 'all' ? null : e.target.value },
      payload: { editFlag: e.target.value },
    });
    this.getList(activeKey, 1, 10, e.target.value);
  };

  // 标记问题人员
  proHandleOk = () => {
    const { activeKey } = this.props;
    this.toggleProModal(false);
    this.getTabNum(activeKey);
  };

  // 取消接单
  cancelReceive = () => {
    const { selectedRowKeys } = this.state;
    const { form } = this.props;
    if (selectedRowKeys.length) {
      this.setState({ cancelReceiveVisible: true });
      form.resetFields(['remark']);
    } else {
      message.warning('请至少选择一条数据！');
    }
  };

  // 提交取消回单办理备注
  submitCancelReceive = () => {
    const { dispatch, form, activeKey } = this.props;
    const { selectedRowKeys } = this.state;
    form.validateFields(['remark'], (err, values) => {
      if (!err) {
        dispatch({
          type: 'adjusttaskrec/cancelReceive',
          payload: { recvOrdAdjTaskId: selectedRowKeys, remark: values.remark },
        }).then(response => {
          if (response.success) {
            this.getList(activeKey);
            this.setState({ cancelReceiveVisible: false });
            message.success('取消接单成功！');
          } else {
            message.warning(`${response.message || '取消接单失败！'}`);
          }
        });
      }
    });
  };

  // 关闭工伤二级户的弹框
  handleCloseReceive = () => {
    this.setState({ receiveModal: false });
    this.getList();
  };

  // 选择工伤二级户
  // eslint-disable-next-line consistent-return
  selectSecAcco = (value, options, index) => {
    const { secondaryList } = this.state;
    if (value.length === 1) {
      return message.warning(`请选择"${options[0].accoName}"的二级户`);
    }
    secondaryList[index].defList = value;
    this.setState({
      secondaryList,
    });
  };

  // 批量接单

  // eslint-disable-next-line consistent-return
  batchOrder = record => {
    const { dispatch } = this.props;
    if (record.defList.length > 1) {
      const pamrea = {
        custId: record.custId,
        injSecId: record.defList[1],
        taskIds: record.taskIds,
      };
      dispatch({
        type: 'adjusttaskrec/batchAcce',
        payload: pamrea,
        callback: res => {
          if (res.success) {
            message.success('接单成功！');
            this.setState({
              receiveModal: false,
              selectedRows: [],
              selectedRowKeys: [],
              secondaryList: [], // 工伤二级户
            });
            this.getList();
          } else {
            message.warning(res.message || '接单失败！');
          }
        },
      });
    } else {
      return message.warning(`请选择二级户`);
    }
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    // eslint-disable-next-line no-unused-vars
    const { dispatch, tabList, editFlag } = this.props;
    const { queryParam } = location;
    if (queryParam) {
      await dispatch({
        type: 'adjusttaskrec/updateModelData',
        payload: {
          expandForm: true,
        },
      });
    } else {
      const newTabList = tabList.map(item => ({ ...item, isHasBadge: false }));
      dispatch({
        type: 'adjusttaskrec/updateModelData',
        payload: { expandForm: false, tabList: newTabList, editFlag: 'all' },
      });
    }
    await this.resetSearch();
    await this.getList(location.query.activeKey, undefined, undefined, queryParam);
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    const { activeKey } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="签约方">
              {getFieldDecorator('sendSuppId', {
                initialValue: formFieldsValue.sendSuppId,
              })(<SendRecvSupplier allowClear onChange={this.getSuppId} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="执行地区">
              {getFieldDecorator('cityId', {
                initialValue: formFieldsValue.cityId,
              })(<Area allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.getTabNum(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      custList,
    } = this.props;
    const { activeKey } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="签约方">
              {getFieldDecorator('sendSuppId', {
                initialValue: formFieldsValue.sendSuppId,
              })(<SendRecvSupplier allowClear onChange={this.getSuppId} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="执行地区">
              {getFieldDecorator('cityId', {
                initialValue: formFieldsValue.cityId,
              })(<Area allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="客户名称">
              {getFieldDecorator('custId', {
                initialValue: formFieldsValue.custId,
              })(
                <Select placeholder="请选择" showSearch optionFilterProp="children" allowClear>
                  {custList &&
                    custList.map(one => (
                      <Option key={one.custId} value={one.custId} title={one.name}>
                        {one.name}
                      </Option>
                    ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="姓名">
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="证件号">
              {getFieldDecorator('idCode', {
                initialValue: formFieldsValue.idCode,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="操作时间">
              {getFieldDecorator('operTime', {
                initialValue: formFieldsValue.operTime,
              })(
                <RangePicker
                  placeholder={['操作开始日期', '操作结束日期']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          {/* <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="操作时间">
              {getFieldDecorator('operTime', {
                initialValue: formFieldsValue.operTime,
              })(
                <RangePicker
                  placeholder={['操作开始日期', '操作结束日期']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              )}
            </FormItem>
          </Col> */}
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.getTabNum(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      pageData,
      countVo,
      loading,
      tabList,
      activeKey,
      editFlag,
      form: { getFieldDecorator },
      cancelReceiveLoading,
      downloadParams,
    } = this.props;
    const {
      selectedRows,
      selectedRowKeys,
      proVisible,
      cancelReceiveVisible,
      receiveModal,
      secondaryList,
    } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 16 } },
    };
    const moreMenu = (
      <Menu>
        {checkPermissions('ns:recvProb:privSupp:addProb') && (
          <Menu.Item key="remarkProb" onClick={() => this.showModal(true)}>
            标记问题人员
          </Menu.Item>
        )}
        {checkPermissions('ns:adj:cancelRecv') && (
          <Menu.Item key="cancelReceive" onClick={this.cancelReceive}>
            取消接单
          </Menu.Item>
        )}
      </Menu>
    );
    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '调整类型',
        dataIndex: 'adjTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '发单时间',
        dataIndex: 'operTime',
        sorter: (a, b) => new Date(b.operTime) - new Date(a.operTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() =>
                router.push(
                  `/receiveordermanage/adjusttask/detail?recvOrdAdjTaskId=${
                    record.recvOrdAdjTaskId
                  }&taskSource=${record.taskSource}&adjType=${record.adjType}`
                )
              }
            >
              查看
            </a>
          </span>
        ),
      },
    ];
    const columnsReceived = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '证件号',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'idCode',
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '调整类型',
        dataIndex: 'adjTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '接单时间',
        dataIndex: 'operTime',
        sorter: (a, b) => new Date(b.operTime) - new Date(a.operTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <div>
            <a
              onClick={() =>
                router.push(
                  `/receiveordermanage/adjusttask/detail?recvOrdAdjTaskId=${
                    record.recvOrdAdjTaskId
                  }&taskSource=${record.taskSource}&adjType=${record.adjType}`
                )
              }
            >
              查看
            </a>
            {checkPermissions('ns:recvAdj:update') ? <Divider type="vertical" /> : null}
            {checkPermissions('ns:recvAdj:update') ? (
              <a
                onClick={() =>
                  router.push(
                    `/receiveordermanage/adjusttask/update?adjType=${record.adjType}&taskSource=${
                      record.taskSource
                    }&recvOrdAdjTaskId=${record.recvOrdAdjTaskId}&isUpdate=true`
                  )
                }
              >
                修改
              </a>
            ) : null}
          </div>
        ),
      },
    ];
    const columnsReplied = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '调整类型',
        dataIndex: 'adjTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '有无修改',
        dataIndex: 'editFlagName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '回单时间',
        dataIndex: 'operTime',
        sorter: (a, b) => new Date(b.operTime) - new Date(a.operTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <a
            onClick={() =>
              router.push(
                `/receiveordermanage/adjusttask/detail?recvOrdAdjTaskId=${
                  record.recvOrdAdjTaskId
                }&taskSource=${record.taskSource}&adjType=${record.adjType}`
              )
            }
          >
            查看
          </a>
        ),
      },
    ];

    // const columnsProblem = [
    //   {
    //     title: '姓名',
    //     dataIndex: 'empName',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //   },
    //   {
    //     title: '证件号',
    //     dataIndex: 'idCode',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //   },
    //   {
    //     title: '客户名称',
    //     dataIndex: 'custName',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     render: text => <TextOverFlow text={text} />,
    //   },
    //   {
    //     title: '接单方',
    //     dataIndex: 'sendSuppName',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     render: text => <TextOverFlow text={text} />,
    //   },
    //   // {
    //   //   title: '问题对象',
    //   //   dataIndex: 'probObj',
    //   //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //   // },
    //   {
    //     title: '问题类型',
    //     dataIndex: 'probTypeIdName',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //   },
    //   {
    //     title: '是否通知',
    //     dataIndex: 'sendSuppFlagName',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //   },
    //   {
    //     title: '操作',
    //     dataIndex: 'operation',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
    //     onCell: () => ({ style: { textAlign: 'center' } }),
    //     render: (text, record) => (
    //       <a
    //         onClick={() =>
    //           router.push(`/receiveordermanage/adjusttask/problem?detId=${record.detId}`)
    //         }
    //       >
    //         查看
    //       </a>
    //     ),
    //   },
    // ];
    const columnsCanceled = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '调整类型',
        dataIndex: 'adjTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '取消时间',
        dataIndex: 'operTime',
        sorter: (a, b) => new Date(b.operTime) - new Date(a.operTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <a
            onClick={() =>
              router.push(
                `/receiveordermanage/adjusttask/detail?recvOrdAdjTaskId=${
                  record.recvOrdAdjTaskId
                }&taskSource=${record.taskSource}&adjType=${record.adjType}`
              )
            }
          >
            查看
          </a>
        ),
      },
    ];

    // 设置工伤二级户
    const secondaryCloumns = [
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '签约方',
        dataIndex: 'sendCorpName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '工伤二级户',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),

        render: (text, record, index) => (
          <FormItem style={{ margin: 0 }}>
            {getFieldDecorator(`secondary[${index}]`, {
              rules: [{ required: true, message: '请选择' }],
              initialValue: record.defList || undefined,
            })(
              <Cascader
                placeholder="请选择"
                options={record.injSecList}
                showSearch
                notFoundContent="暂无工伤二级户"
                onChange={(value, options) => this.selectSecAcco(value, options, index)}
                changeOnSelect
                style={{ width: 400 }}
              />
            )}
          </FormItem>
        ),
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        // eslint-disable-next-line arrow-body-style
        render: (text, record) => {
          return (
            <div>
              <a onClick={() => this.batchOrder(record)}>批量接单</a>
            </div>
          );
        },
      },
    ];
    const sensed = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="ns:recvAdj:recv" noMatch={null}>
            <Button type="primary" style={{ marginRight: 8 }} onClick={this.receive}>
              接单
            </Button>
          </Authorized>
          <Authorized noMatch={null} authority="ns:rcvrAdjProb:addProb">
            <Button
              onClick={() => {
                this.showModal(true);
              }}
            >
              标记问题人员
            </Button>
          </Authorized>
          {countVo && (
            <div style={{ margin: '16px 16px 0 0', width: '200%' }}>
              <Alert
                message={
                  <Fragment>
                    客户数量
                    <a style={{ margin: '0 20px' }}>{(countVo && countVo.custAmount) || 0}</a>
                    员工数量
                    <a style={{ margin: '0 20px' }}>{(countVo && countVo.empAmount) || 0}</a>
                    {countVo && countVo.empAmount !== 0 ? (
                      <Link to="/receiveordermanage/adjusttask/protdetail">查看协议</Link>
                    ) : null}
                  </Fragment>
                }
                type="info"
                showIcon
              />
            </div>
          )}

          {/* <Authorized authority="" noMatch={null}>
            <Button
              // onClick={() => router.push('/receiveordermanage/adjusttask/changeprotocol')}
              onClick={() => {
                message.warning('努力开发中。。。');
              }}
              style={{ marginRight: 8 }}
            >
              更换协议
            </Button>
          </Authorized> */}
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="recvOrdAdjTaskId"
          columns={columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const received = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="ns:recvAdj:detail" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              // onClick={() =>
              //   router.push(`/receiveordermanage/adjusttask/update?recvOrdAdjTaskId=${selectedRowKeys}`)
              // }
              onClick={() => {
                this.adjustReceipt();
              }}
            >
              回单
            </Button>
          </Authorized>
          <Authorized authority="ns:recvAdj:export" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              icon={<DownloadOutlined />}
              onClick={() => {
                this.export();
              }}
            >
              导出
            </Button>
          </Authorized>
          <Dropdown overlay={moreMenu}>
            <Button>
              更多
              <DownOutlined />
            </Button>
          </Dropdown>
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="recvOrdAdjTaskId"
          columns={columnsReceived}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const replied = (
      <div>
        <div style={{ marginBottom: 16 }}>
          <Authorized authority="ns:recvAdj:export" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              icon={<DownloadOutlined />}
              onClick={() => {
                this.export();
              }}
            >
              导出
            </Button>
          </Authorized>
          <div style={{ float: 'right' }}>
            <RadioGroup className={styles.floatRight} value={editFlag} onChange={this.editFlag}>
              <RadioButton value="all">全部</RadioButton>
              <RadioButton value={2}>无修改</RadioButton>
              <RadioButton value={1}>有修改</RadioButton>
            </RadioGroup>
          </div>
        </div>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="recvOrdAdjTaskId"
          columns={columnsReplied}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const problem = (
      <div>
        <div style={{ marginBottom: 16 }}>
          <Authorized noMatch={null} authority="ns:rcvrAdjProb:addProbFdbk">
            <Button
              type="primary"
              onClick={() =>
                router.push('/receiveordermanage/adjusttask/batchfeedback?busiType=10')
              }
              style={{ marginRight: 8 }}
            >
              批量反馈
            </Button>
          </Authorized>
          {/* <Authorized authority="ns:recvProb:sendSupp:notice" noMatch={null}>
          <Button
            style={{ margin: '0 8px 16px 0' }}
            onClick={() => {
              this.notifycontg();
            }}
          >
            通知签约方
          </Button>
        </Authorized> */}
          <Authorized noMatch={null}>
            <ProExportBtn selectedRowKeys={selectedRowKeys} downloadParams={downloadParams} />
          </Authorized>
        </div>
        {/* <ProTable
          columns={columnsProblem}
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          isProObj
          data={pageData}
          rowKey="detId"
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
          proUrl="/customservicemanage/addemployee/problem"
        /> */}
        <ProTable
          onRef={e => {
            this.setState({ proTable: e });
          }}
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          onSelectRow={this.handleSelectRows}
          proUrl="/receiveordermanage/adjusttask/problem"
          busiType="10"
        />
      </div>
    );
    const canceled = (
      <div>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="recvOrdAdjTaskId"
          columns={columnsCanceled}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 获取页签组件
    const getTabPane = key => {
      switch (key) {
        case '1':
          return sensed;
        case '2':
          return received;
        case '3':
          return replied;
        case '4':
          return problem;
        case '5':
          return canceled;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tabCard}>
          <div className={styles.tableList}>
            <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
              {tabList.map(pane => (
                <TabPane
                  tab={<Badge dot={pane.isHasBadge}>{pane.itemName}</Badge>}
                  key={pane.itemCode}
                >
                  {getTabPane(pane.itemCode)}
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Card>
        {proVisible && (
          <ProModal
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            busiType="10"
            onOk={this.proHandleOk}
            onCancel={() => this.toggleProModal(false)}
            isProType
          />
        )}
        <Modal
          title="取消接单"
          destroyOnClose
          visible={cancelReceiveVisible}
          onOk={this.submitCancelReceive}
          onCancel={() => this.setState({ cancelReceiveVisible: false })}
          confirmLoading={cancelReceiveLoading}
        >
          <FormItem {...formItemLayout} label="办理备注">
            {getFieldDecorator('remark', {
              rules: [{ required: cancelReceiveVisible, message: '请输入' }],
            })(
              <TextArea
                placeholder="请输入"
                autosize={{ minRows: 3, maxRows: 6 }}
                maxLength="100"
              />
            )}
          </FormItem>
        </Modal>
        <Modal
          title="设置工伤二级户"
          visible={receiveModal}
          width={1200}
          closable={false}
          destroyOnClose
          footer={
            <Button type="primary" onClick={() => this.handleCloseReceive()}>
              关闭
            </Button>
          }
        >
          <div>
            <Table
              loading={loading}
              dataSource={secondaryList}
              rowKey="sendSuppId"
              columns={secondaryCloumns}
            />
          </div>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
